/**
 * 
 */
package info.niwota.home.fm;

import info.niwota.home.R;
import instant.openvfs.home.Debug;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class ShortcutActivity extends Activity {

	public static final String SHORTCUT_SCHEME = "v-bin-shortcut";
	private static final String LOG_TAG = "ShortcutActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		final Intent intent = getIntent();
		final String action = intent.getAction();
		//app shortcut
		if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
			if (Debug.DEBUG) {
				Log.d(LOG_TAG, "Creating shortcut for opening application");
			}
			setupShortcut();
			finish();
			return;
		}

		Uri uri = intent.getData();
		//
		String scheme = uri.getScheme();
		String path = uri.getPath();
		
		if (Debug.DEBUG) {
			Log.d(LOG_TAG, this.getClass() + ": " + uri + " scheme: "
				+ scheme + " path: " + path);
		}

		// respond to v-bin-shortcut:// action
		if (scheme.equals(SHORTCUT_SCHEME)) {
			if (Debug.DEBUG) {
				Log.d(LOG_TAG, "Creating shortcut for " + path);
			}
			createShortcut(uri);
			finish();
			return;
		}
		Toast.makeText(this, "Can't create shortcut for "+path, Toast.LENGTH_LONG);
		finish();
	}

	private void createShortcut(Uri uri) {
		// content://v:/path
		
		if (Debug.DEBUG) {
			Log.d(LOG_TAG, "creating shortcut for: " + uri);
		}
		String path = Utils.path(uri);
		Uri shortcutUri = Uri.parse("v://" + path);

		Intent shortcutIntent = new Intent(Intent.ACTION_VIEW, shortcutUri);
		
		shortcutIntent.setClassName(this, FileExploreActivity.class.getName());
		shortcutIntent.addCategory(Intent.CATEGORY_BROWSABLE);
		//
		Intent intent = createIntent(path, R.drawable.shortcut,
				shortcutIntent);
		intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		sendBroadcast(intent);

		Toast.makeText(this, "Shortcut created. ", Toast.LENGTH_SHORT).show();
	}

	private Intent createIntent(String name, int icon, Intent shortcutIntent) {
		Intent intent = new Intent();
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
		Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this,
				icon);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
		return intent;
	}

	private void setupShortcut() {
		Intent shortcutIntent = new Intent(this,FileExploreActivity.class);
		Intent intent = createIntent(getString(R.string.app_name),
				R.drawable.openvfs, shortcutIntent);
		setResult(RESULT_OK, intent);
	}
}
